package com.dronff.gvm.memorymanager;

/**
 * @author: tyf
 * @date: 2022/9/9 12:24
 * @description: todo(为子内存提供的安全的byte[]
 */
public class SafeBytes {
    private byte[] bytes;
    private Memory memory;

    public SafeBytes(byte[] bytes,Memory memory){
        if(memory.getParent() == null){
            throw new IllegalArgumentException("memory is not a child memory");
        }
        this.bytes = bytes;
        this.memory = memory;
    }
    public byte get(int i){
        return get0(i + memory.getOffset());
    }
    private byte get0(int i){
        if(!checkIndex(i)){
            throw new IndexOutOfBoundsException("memory read err :index out of bounds");
        }
        return bytes[i];
    }
    public void set(int i,byte byt){
        set0(i+ memory.getOffset(),byt);
    }
    private void set0(int i,byte byt){
        if(!checkIndex(i)){
            throw new IndexOutOfBoundsException("memory set err :index out of bounds");
        }
        checkIndex(i);
        bytes[i] = byt;
    }
    public boolean checkIndex(int i){
        if(i >= memory.getOffset() + memory.getSize()){
            return false;
        }
        return true;
    }
    public void appendByte(byte byt){
        if(this.memory.getCurrentIndex() >= this.memory.getSize()){
            throw new IndexOutOfBoundsException("memory append err :index out of bounds");
        }
        this.bytes[this.memory.getCurrentIndex()] = byt;
        this.memory.setCurrentIndex(this.memory.getCurrentIndex()+1);
    }
}
